using AutoMapper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmartLink.DTOS;
using SmartLink.DTOS.Account;
using SmartLink.Application.IServices;
using SmartLink.Domain;
using SmartLink.Domain.Entity;
using SmartLink.Domain.Services;
using SmartLink.EnumLibrary;
using SmartLink.Infrastructure;
using SmartLink.Infrastructure.Cache;
using SmartLink.IRepository;
using SmartLink.Domain.IServices;
using SmartLink.Domain.ExpandEntity.Base;
using SmartLink.Infrastructure.Mappers;
using SmartLink.DTOS.SysBasic;
using SmartLink.DTOS.Permission;
using Newtonsoft.Json;
using System.Web;
using System.Net;
using System.IO;
using SmartLink.Repository;
using System.Data.Common;

namespace SmartLink.Application.Services
{
    public class AccountAppServices : IAccountAppServices
    {
        //通行证服务
        private ISYS_UserServices _sysUserServices;
        //记录登录日志
        private ISYS_UserLoadingServices _sysUserLoadingServices;
        //组织架构
        private IBIZ_OrganizationDepartmentServices _bIZ_OrganizationDepartmentServices;
        //账号-组织机构对应表
        private IBIZ_UserToOrganizationServices _bIZ_UserToOrganizationServices;
        //APP 调用
        private IPermissionAppServices _IPermissionAppServices;


        private IPermissionServices _permissionServices;
        private ISYS_UserRepo _UserRepository;
        private IBIZ_UserToPlateRepo _BIZ_UserToPlateRepo;

        public AccountAppServices(ISYS_UserServices iSYS_UserServices,
                                  ISYS_UserLoadingServices iSYS_UserLoadingServices,
                                  IBIZ_OrganizationDepartmentServices iBIZ_OrganizationDepartmentServices,
                                  IBIZ_UserToOrganizationServices iBIZ_UserToOrganizationServices,
                                  IPermissionAppServices iPermissionAppServices,
                                  IPermissionServices permissionServices,
                                  ISYS_UserRepo userRepository,
                                  IBIZ_UserToPlateRepo bIZ_UserToPlateRepo)
        {
            _sysUserServices = iSYS_UserServices;
            _sysUserLoadingServices = iSYS_UserLoadingServices;
            _bIZ_OrganizationDepartmentServices = iBIZ_OrganizationDepartmentServices;
            _bIZ_UserToOrganizationServices = iBIZ_UserToOrganizationServices;
            _IPermissionAppServices = iPermissionAppServices;
            _permissionServices = permissionServices;
            _UserRepository = userRepository;
            _BIZ_UserToPlateRepo = bIZ_UserToPlateRepo;
        }

        #region 登录模块

        public Results<LoginResponseDTO> Login(LoginDTO model)
        {
            var checkResult = _sysUserServices.CheckLogin(model.UserName, model.PassWord);
            if (checkResult.ResultType != OperationResultType.Success)
                return InfrastructureAppService.Response<LoginResponseDTO>(checkResult.Message, StateCodeEnum.失败);

            var user = checkResult.AppendData as SYS_User;
            var token = JWTHelper.GenToken(user.ID, false);

            CurrentUserInfo curUserInfo = _sysUserServices.GetCurrentUserInfo(user.ID);
            UserInfoCaches.SetLoginCache(token, curUserInfo);

            //登陆回写
            LoginWriteBack(user, model.Ip);
            //登陆日志
            //AddLoginLogAsync(model, user.ID, user.AccountName);

            LoginResponseDTO loginResponseDTO = new LoginResponseDTO();
            loginResponseDTO.Token = token;
            loginResponseDTO.CurUserInfo = curUserInfo;
            try
            {
                loginResponseDTO.UserPermission = GetUserRights(user.ID);
            }
            catch (NullReferenceException ex)
            {
                return InfrastructureAppService.Response<LoginResponseDTO>(ex.Message, StateCodeEnum.失败);
            }

            var userPermission = new UserPermissionDTO
            {
                Modules = Mapper.Map<IList<SysModuleDTO>>(loginResponseDTO.UserPermission.Modules),
                ModuleFunctions = loginResponseDTO.UserPermission.ModuleFunctions
            };
            UserInfoCaches.SetActionPermissionCache(user.ID, userPermission);

            //缓存角色权限
            if (RolePermissionCache.Get(curUserInfo.RoleId) == null)
            {
                var rolePermissions = _IPermissionAppServices.GetRolePermissions(curUserInfo.RoleId);
                RolePermissionCache.Set(curUserInfo.RoleId, rolePermissions);
            }
            //缓存角色用户关联
            RoleToUsersCache.SetUser(curUserInfo.RoleId, curUserInfo.UserId);

            return InfrastructureAppService.Response(loginResponseDTO);
        }

        public Results<bool> Logout(int userId)
        {
            //UserInfoCaches.RemoveUserInfo(userId);
            UserInfoCaches.RemoveUserRightsCache(userId);
            return InfrastructureAppService.Response(true, StateCodeEnum.成功.ToString(), StateCodeEnum.成功.GetHashCode());
        }

        public CurrentUserInfo GetCurrentUserInfo(int userId)
        {
            return _sysUserServices.GetCurrentUserInfo(userId);
        }

        /// <summary>
        /// 记录登录日志
        /// </summary>
        public async Task AddLoginLogAsync(LoginDTO model, int uid, string accountName)
        {
            await Task.Run(() =>
            {
                var logModel = new SYS_UserLoading
                {
                    LoadingTime = DateTime.Now,
                    LoadingUser = accountName,
                    LoadingIP = model.Ip,
                    ClientType = ClientEnum.PC.GetHashCode(),
                    ClientModel = model.ClientModel,
                    SoftVersion = model.SoftVersion,
                    ClientVersion = model.ClientVersion,
                    LoadingUserID = uid,
                    LoadingArea = model.LoadingArea
                };
                if (string.IsNullOrWhiteSpace(logModel.LoadingArea))
                {// 前端上传优先
                    logModel.LoadingArea = IpToAddressRemote(model.Ip);
                }
                _sysUserLoadingServices.AddLoginLog(logModel);
            });
        }
        /// <summary>
        /// 登陆回写
        /// </summary>
        public void LoginWriteBack(SYS_User user, string loginIp)
        {
            user.LastLoginTime = DateTime.Now;
            user.LastLoginIP = loginIp;
            _sysUserServices.Update(user);
        }
        #endregion

        #region 用户管理

        public Results<PageData<UserListItemDTO>> GetUserList(UserPagePara pagePara, int curUserID)
        {
            pagePara.OID = (pagePara.OID == ConstData.SelectAllOptionValue) ? null : pagePara.OID;
            pagePara.ODID = (pagePara.ODID == ConstData.SelectAllOptionValue) ? null : pagePara.ODID;
            UserStatusEnum? userStatus = (!pagePara.UserStatus.HasValue || pagePara.UserStatus == ConstData.SelectAllOptionValue) ? null : (UserStatusEnum?)pagePara.UserStatus;

            var pagination = pagePara.ToPagination();
            var list = _sysUserServices.GetPaged(pagePara.OID, pagePara.ODID, userStatus, pagePara.KeyValue, curUserID, pagination);
            IEnumerable<UserListItemDTO> dto = list.Select(a => new UserListItemDTO
            {
                ID = Convert.ToInt32(a.ID),
                AccountName = a.AccountName,
                NickName = a.NickName,
                UserMobile = a.UserMobile,
                UserPhone = a.UserPhone,
                DepartmentName = a.DepartmentName,
                RoleName = a.RoleName,
                UserStatus = a.UserStatus,
                UserStatusText = a.UserStatus == null ? string.Empty : EnumHelper.GetDesription<UserStatusEnum>(Convert.ToInt32(a.UserStatus)),
                CreateTime = a.CreateTime,
                Creator = a.Creator,
                LastLoginTime = a.LastLoginTime,
                OID = a.OID,
                ROID = a.ROID
            });

            var pageData = new PageData<UserListItemDTO>() { CurrentData = dto, TotalCount = pagination.TotalCount };
            return InfrastructureAppService.Response(pageData);
        }

        public Results<UserInfoDTO> GetUserInfo(int id)
        {
            var user = _sysUserServices.GetUserInfo(id);
            var dto = DynamicToStaticHelper.ToStatic<UserInfoDTO>(user);
            return InfrastructureAppService.Response(dto);
        }

        public Results AddUser(AddUserDTO userModel)
        {
            if (_sysUserServices.ExistAcountName(userModel.AccountName))
                return InfrastructureAppService.Response("该账户名已经存在！", StateCodeEnum.失败);

            if (!string.IsNullOrEmpty(userModel.UserEmail))
            {
                if (_sysUserServices.ExistUserEmail(userModel.UserEmail))
                    return InfrastructureAppService.Response("该邮箱已被使用！", StateCodeEnum.失败);
            }

            SYS_User user = Mapper.Map<SYS_User>(userModel);
            user.Create(CurrentUser.Current.UserId);
            BIZ_UserToOrganization userToOrg = new BIZ_UserToOrganization();
            userToOrg.UserID = user.ID;
            userToOrg.OID = userModel.OID;
            userToOrg.OD_ID = userModel.DeptId;

            user.PassWord = SYS_UserServices.EncryptPassword(ConstData.DefaultUserPassword, user.CreateTime);
            bool sucFlag = _sysUserServices.Add(user, userToOrg);
            if (sucFlag)
                return InfrastructureAppService.Response();
            else
                return InfrastructureAppService.Response(StateCodeEnum.失败.ToString(), StateCodeEnum.失败);
        }

        public Results UpdateUserBasicInfo(UserBasicInfoUpdateDTO userDto)
        {
            SYS_User originalUser = _sysUserServices.GetById(userDto.ID);
            var originalUto = _bIZ_UserToOrganizationServices.GetByUserId(userDto.ID);
            bool modifyDept = originalUto.OD_ID != userDto.DeptId;
            bool disabling = userDto.UserStatus == UserStatusEnum.禁用 && userDto.UserStatus != originalUser.UserStatus;

            Mapper.Map(userDto, originalUser, typeof(UserBasicInfoUpdateDTO), typeof(SYS_User));
            _sysUserServices.Update(originalUser, originalUto.OID, modifyDept ? userDto.DeptId : null);
            if (modifyDept || disabling)
                UserInfoCaches.SetExpires(userDto.ID);
            return InfrastructureAppService.Response();
        }

        public Results DeleteUser(int userId)
        {
            _sysUserServices.Delete(userId);
            UserInfoCaches.RemoveUserInfo(userId);
            return InfrastructureAppService.Response();
        }

        public Results ForceUpdatePassword(string password)
        {
            var opResult = _sysUserServices.ForceUpdatePassword(password);
            return InfrastructureAppService.Transmit(opResult);
        }

        public Results ResetPassword(int userId)
        {
            var opResult = _sysUserServices.ResetPassword(userId);
            return InfrastructureAppService.Transmit(opResult);
        }

        public Results UpdateUserStatus(UpdateUserStatusDTO model)
        {
            SYS_User user = _sysUserServices.GetById(model.UserId);
            if (model.UserStatus == user.UserStatus)
                return InfrastructureAppService.Response(StateCodeEnum.成功.ToString(), StateCodeEnum.成功.GetHashCode());

            user.UserStatus = model.UserStatus;
            bool sucFlag = _sysUserServices.Update(user);
            UserInfoCaches.RemoveUserInfo(user.ID);
            if (sucFlag)
                return InfrastructureAppService.Response(StateCodeEnum.成功.ToString(), StateCodeEnum.成功.GetHashCode());
            else
                return InfrastructureAppService.Response(StateCodeEnum.失败.ToString(), StateCodeEnum.失败.GetHashCode());
        }

        public Results<IEnumerable<UserSelectListItemDTO>> GetUserSelectList(int orgId, bool isDept)
        {
            var userList = _sysUserServices.GetUserSelectList(orgId, isDept);
            var dtoList = Mapper.Map<IEnumerable<UserSelectListItemDTO>>(userList);
            return InfrastructureAppService.Response(dtoList);
        }

        public Results ModifyPassword(PwdModifyDTO modifyPwdDTO, int userId)
        {
            SYS_User originalUser = _sysUserServices.GetById(userId);
            string modifiedPwd = SecurityHelper.ToMd5(modifyPwdDTO.OldPassWord.ToUpper() + originalUser.CreateTime.ToString("yyyyMMdd"));
            if (modifiedPwd == originalUser.PassWord)
            {
                string newPwd = SecurityHelper.ToMd5(modifyPwdDTO.NewPassWord.ToUpper() + originalUser.CreateTime.ToString("yyyyMMdd"));
                originalUser.PassWord = newPwd;
                bool success = _sysUserServices.Update(originalUser);
                if (success)
                {
                    var token = JWTHelper.GenToken(userId, false);
                    var key = "UserToken_" + userId;
                    UserInfoCaches.SetUserToken(key, "token", token);
                    //UserInfoCaches.SetUserToken(key, "appToken", token);
                    return InfrastructureAppService.Response("密码修改成功", StateCodeEnum.成功.GetHashCode());
                }
                else
                    return InfrastructureAppService.Response("密码修改失败", StateCodeEnum.失败.GetHashCode());
            }
            else
            {
                return InfrastructureAppService.Response("原密码填写错误", StateCodeEnum.失败.GetHashCode());
            }
        }

        #endregion

        #region Private

        /// <summary>
        /// 用户权限
        /// </summary>
        /// <returns></returns>
        private UserRightsDto GetUserRights(int userId)
        {
            try
            {
                UserRightsDto userRightsDto = new UserRightsDto();
                //userRightsDto.MenuRights = _IPermissionAppServices.GetRightMenuTree(userId).Data;
                //userRightsDto.ActionRights = _IPermissionAppServices.GetActionPermissions(userId).Data;
                //userRightsDto.DataRights = _IPermissionAppServices.GetDataPermissions(userId).Data;

                var modules = _permissionServices.GetUserAuthorizedModules(userId);
                userRightsDto.Modules = modules;   // 之前的树形结构换成 平行结构  modules.ListToTree();
                userRightsDto.ModuleFunctions = Mapper.Map<IList<SysModuleFunctionDTO>>(_permissionServices.GetUserAuthorizedFunctions(userId));
                foreach (var moduleFunction in userRightsDto.ModuleFunctions)
                {
                    moduleFunction.ModuleCode = modules.Where(a => a.ID == moduleFunction.ModuleID).Select(a => a.Code).SingleOrDefault();
                }
                return userRightsDto;
            }
            catch (NullReferenceException)
            {
                throw;
            }
        }
        /// <summary>
        /// 远程请求第三方ip转地址服务
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        private string IpToAddressRemote(string ip)
        {
            try
            {
                var html = HttpRequestHelper.Get("http://whois.pconline.com.cn/ip.jsp?ip=" + ip, Encoding.GetEncoding("GBK"));
                return string.IsNullOrWhiteSpace(html) ? null : html.Trim().Split(' ')[0];
            }
            catch (Exception)
            {
                Infrastructure.Logger.AppLogger.Info($"IP转地理位置失败。（IP：{ip}）");
                return null;
            }
        }

        #endregion

        #region old

        /// <summary>
        /// 删缓存 达到只从数据库获取
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public Results<UserRightsDto> GetUserAllRights(int userId)
        {
            try
            {
                UserInfoCaches.RemoveUserRightsCache(userId);
                UserRightsDto userRightsDto = GetUserRights(userId);
                return InfrastructureAppService.Response<UserRightsDto>(userRightsDto, StateCodeEnum.成功.ToString(), StateCodeEnum.成功.GetHashCode());
            }
            catch (Exception)
            {

                throw;
            }
        }

        #endregion



        #region 微信授权登录

        public Results<WXLoginResponseDTO> WXAuthorization(WXAuthorizationRequestDTO requestDTO)
        {
            //入参校验
            WXLoginResponseDTO responseDTO = new WXLoginResponseDTO();
            try
            {
                string url = "https://api.weixin.qq.com/sns/jscode2session";

                var parameters = new Dictionary<string, string>();
                parameters.Add("appid", requestDTO.APPID);
                parameters.Add("secret", requestDTO.SECRET);
                parameters.Add("js_code", requestDTO.CODE);
                parameters.Add("grant_type", requestDTO.GRANTTYPE);

                string result = HttpHelper.sendPost(url, parameters, "get");
                var response = JsonConvert.DeserializeObject<WX_AuthorizationResponse>(result);

                if (response.openid != null)
                {
                    SYS_User curUser = _UserRepository.GetUserByOpenID(response.openid);
                    if (curUser == null)
                    {
                        curUser = new SYS_User();
                        curUser.IsDel = false;
                        curUser.OpenID = response.openid;
                        curUser.UserType = (int)UserTypeEnum.车主用户;
                        curUser.AccountName = "";
                        curUser.PassWord = "";
                        curUser.CreateTime = DateTime.Now;
                        int userid = _UserRepository.Add(curUser);
                        curUser.ID = userid;
                    }
                    responseDTO.Token = JWTHelper.GenToken(curUser.ID, true);
                    CurrentUserInfo curUserInfo = _sysUserServices.GetCurrentUserInfo(curUser.ID);
                    UserInfoCaches.SetLoginCache(responseDTO.Token, curUserInfo);
                }
                else
                {
                    return InfrastructureAppService.Response<WXLoginResponseDTO>(responseDTO, "登陆失败", StateCodeEnum.失败.GetHashCode());
                }
                InfrastructureAppService.Response<WXLoginResponseDTO>(responseDTO);
            }
            catch (Exception ex)
            {
                return InfrastructureAppService.Response<WXLoginResponseDTO>(ex.Message, StateCodeEnum.失败);
            }
            return InfrastructureAppService.Response<WXLoginResponseDTO>(responseDTO);
        }



        /// <summary>
        /// 发送验证码
        /// </summary>'
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        public string SendValidateCode(string openId, string phoneNumber)
        {
            // 设置为您的apikey(https://www.yunpian.com)可查
            string apikey = "f40aa781be1a5d0434957f87f97d1795";
            // 发送的手机号
            string mobile = phoneNumber;
            // 发送模板编号
            int tpl_id = 2216562;
            // 发送模板内容
            mobile = HttpUtility.UrlEncode(mobile, Encoding.UTF8);
            Random rd = new Random();
            string validCode = rd.Next(100000, 1000000).ToString();

            //缓存到redis
            ValidateCodeInfo validateCodeInfo = new ValidateCodeInfo();
            validateCodeInfo.Code = validCode;
            validateCodeInfo.ExpiredUnixTime = TimeHelper.GetUnixTime(DateTime.Now.AddSeconds(60));
            validateCodeInfo.PhoneNumber = phoneNumber;
            string codeInfo = JsonEx.SerializeObject(validateCodeInfo);
            ValidateCodeCache.SetValidateCode(openId, codeInfo);
            
            string tpl_value = HttpUtility.UrlEncode(
            HttpUtility.UrlEncode("#code#", Encoding.UTF8) + "=" + HttpUtility.UrlEncode(validCode, Encoding.UTF8));
            // 指定模板发送短信url
            string url_tpl_sms = "https://sms.yunpian.com/v2/sms/tpl_single_send.json";
            string data_tpl_sms = "apikey=" + apikey + "&mobile=" + mobile +
                "&tpl_id=" + tpl_id.ToString() + "&tpl_value=" + tpl_value;

            string reMsg = HttpPost(url_tpl_sms, data_tpl_sms);
            return reMsg;
        }


        private string HttpPost(string Url, string postDataStr)
        {
            string reMsg = string.Empty;
            byte[] dataArray = Encoding.UTF8.GetBytes(postDataStr);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = dataArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(dataArray, 0, dataArray.Length);
            dataStream.Close();
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                String res = reader.ReadToEnd();
                reader.Close();
                var newObj = JsonConvert.DeserializeObject<dynamic>(res);
                if (newObj["code"] == null)
                {
                    reMsg = "失败";
                }
                Newtonsoft.Json.Linq.JValue jValue = (Newtonsoft.Json.Linq.JValue)(newObj["code"]);
                Newtonsoft.Json.Linq.JValue jValueMsg = (Newtonsoft.Json.Linq.JValue)(newObj["msg"]);
                string errorCode = jValue.Value.ToString();
                string msg = jValueMsg.Value.ToString();
                if (errorCode == "1")
                    reMsg = msg;
                else
                    reMsg = string.Empty;
            }
            catch (Exception e)
            {
                reMsg ="验证码发送次数超过限制";
            }
            return reMsg;
        }


        /// <summary>
        /// 验证码确认
        /// </summary>
        /// <param name="openID"></param>
        /// <param name="codeDto"></param>
        /// <returns></returns>
        public Results ComfirmCode(string openID, ValidateCodeDTO codeDto)
        {
            SYS_User user = _UserRepository.GetUserByOpenID(openID);
            string codeInfoStr = ValidateCodeCache.GetValidateCode(openID);
            ValidateCodeInfo codeInfo = JsonEx.DeserializeObject<ValidateCodeInfo>(codeInfoStr);
            if (codeInfo.Code == codeDto.ValidateCode)
            {
                string nowUnixTime = TimeHelper.GetUnixTime(DateTime.Now);
                if (nowUnixTime.CompareTo(codeInfo.ExpiredUnixTime) > 0)
                    return InfrastructureAppService.Response("验证码已过期,请重新验证", StateCodeEnum.失败.GetHashCode());
                else
                {
                    //手机号写入
                    user.UserPhone = codeInfo.PhoneNumber;
                    _UserRepository.Update(user);
                    ValidateCodeCache.DeleteValidateCode(openID);
                    return InfrastructureAppService.Response();
                }
            }
            else
                return InfrastructureAppService.Response("验证码输入错误", StateCodeEnum.失败.GetHashCode());
        }



        #endregion

        /// <summary>
        /// 绑定车牌
        /// </summary>
        /// <param name="curUserId"></param>
        /// <param name="plateDto"></param>
        /// <returns></returns>
        public Results BindVehiclePlate(int curUserId, PlateDto plateDto)
        {
            IList<BIZ_UserToPlate> existPlates = _BIZ_UserToPlateRepo.GetPlateByUserID(curUserId);
            if (existPlates != null)
            {
                foreach (BIZ_UserToPlate plate in existPlates)
                {
                    if (plate.Plate == plateDto.Plate)
                        return InfrastructureAppService.Response("车牌已经绑定过了!", StateCodeEnum.失败.GetHashCode());
                }
            }

            BIZ_UserToPlate userPlate = new BIZ_UserToPlate();
            userPlate.UserID = curUserId;
            userPlate.Plate = plateDto.Plate;
            userPlate.IsDeafault = existPlates.Count == 0 ? true : false;
            userPlate.Creator = curUserId;
            userPlate.CreateTime = DateTime.Now;
            userPlate.Updater = curUserId;
            userPlate.UpdateTime = DateTime.Now;
            bool flag = _BIZ_UserToPlateRepo.Add(userPlate) > 0;
            return InfrastructureAppService.Response();
        }

        /// <summary>
        ///  
        /// </summary>
        /// <param name="curUserId"></param>
        /// <returns></returns>
        public Results<IList<UserToPlateDTO>> GetUserVehiclePlates(int curUserId)
        {
            IList<BIZ_UserToPlate> existPlates = _BIZ_UserToPlateRepo.GetPlateByUserID(curUserId);
            IList<UserToPlateDTO> dtoList = Mapper.Map<IList<UserToPlateDTO>>(existPlates);
            return InfrastructureAppService.Response<IList<UserToPlateDTO>>(dtoList);
        }

        /// <summary>
        /// 是否绑定车牌
        /// </summary>
        /// <param name="curUserId"></param>
        /// <returns></returns>
        public Results<bool> GetPlateBindStatus(int curUserId)
        {
            IList<BIZ_UserToPlate> existPlates = _BIZ_UserToPlateRepo.GetPlateByUserID(curUserId);
            if (existPlates.Count > 0)
                return InfrastructureAppService.Response<bool>(true);
            return InfrastructureAppService.Response<bool>(false);
        }

        /// <summary>
        /// 修改默认车牌
        /// </summary>
        /// <param name="curUserID"></param>
        /// <param name="plateIdDTO"></param>
        /// <returns></returns>
        public Results SetDefaultPlate(int curUserID, DefaultPlateDTO plateIdDTO)
        {
            bool results = false;

            IList<BIZ_UserToPlate> existPlates = _BIZ_UserToPlateRepo.GetPlateByUserID(curUserID);
            foreach (BIZ_UserToPlate userPlate in existPlates)
            {
                if (userPlate.ID == plateIdDTO.ID)
                    userPlate.IsDeafault = true;
                else
                    userPlate.IsDeafault = false;
            }

            using (DbTransaction tran = _BIZ_UserToPlateRepo.TranCreate())
            {
                try
                {
                    foreach (BIZ_UserToPlate userPlate in existPlates)
                    {
                        _BIZ_UserToPlateRepo.Update(userPlate, tran);
                    }
                    tran.Commit();
                    results = true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    results = false;
                }
                finally
                {
                    _BIZ_UserToPlateRepo.TranClose(tran);
                }
            }

            if (results)
                return InfrastructureAppService.Response();
            else
                return InfrastructureAppService.Response("设置失败", StateCodeEnum.失败.GetHashCode());
        }

        public Results DeletePlate(int curUserID, DefaultPlateDTO plateIdDTO)
        {
            bool results = false;
            //删除之后 重新设置默认
            IList<BIZ_UserToPlate> existPlates = _BIZ_UserToPlateRepo.GetPlateByUserID(curUserID);
            foreach (BIZ_UserToPlate userPlate in existPlates)
            {
                if (userPlate.ID != plateIdDTO.ID)
                {
                    userPlate.IsDeafault = true;
                    break;
                }
            }

            using (DbTransaction tran = _BIZ_UserToPlateRepo.TranCreate())
            {
                try
                {
                    foreach (BIZ_UserToPlate userPlate in existPlates)
                    {
                        if (userPlate.ID == plateIdDTO.ID)
                            _BIZ_UserToPlateRepo.Delete(userPlate, tran);
                        else
                            _BIZ_UserToPlateRepo.Update(userPlate, tran);
                    }
                    tran.Commit();
                    results = true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    results = false;
                }
                finally
                {
                    _BIZ_UserToPlateRepo.TranClose(tran);
                }

            }

            if (results)
                return InfrastructureAppService.Response();
            else
                return InfrastructureAppService.Response("删除失败", StateCodeEnum.失败.GetHashCode());

        }

    }
}
